package com.mxx.common.http;

import com.alibaba.fastjson.JSONObject;
import com.mxx.common.conv.JsonUtil;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * @Author itzgyw
 * @Date 2020-01-14
 * @Time 14:41
 * @Description:
 */

public class OkHttpResponse implements HttpResponse {
    private int code;
    private Headers headers;
    private boolean successful;
    private boolean redirect;
    private String contentType;
    private long length;
    private byte[] body;
    private Integer statusCode;
    private Charset charset;

    public static OkHttpResponse read(Response response) throws IOException {
        return new OkHttpResponse(response);
    }

    public OkHttpResponse(Response response) throws IOException {
        this.code = response.code();
        this.headers = response.headers();
        this.successful = response.isSuccessful();
        this.redirect = response.isRedirect();
        ResponseBody body = response.body();
        MediaType mediaType = body.contentType();
        if (mediaType != null) {
            this.contentType = mediaType.toString();
            this.charset = mediaType.charset();
        }
        if (this.charset == null) {
            this.charset = StandardCharsets.UTF_8;
        }
        this.statusCode = response.code();
        this.length = body.contentLength();
        this.body = body.bytes();
        response.close();
    }


    @Override
    public boolean isSuccessful() {
        return this.code == 200;
    }

    @Override
    public String getBody() {
        return new String(this.body, this.charset);
    }

    @Override
    public byte[] getByte() {
        return this.body;
    }

    @Override
    public int statusCode() {
        return this.statusCode;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public long getContentLength() {
        return this.length;
    }

    @Override
    public Charset getCharset() {
        return this.charset;
    }

    @Override
    public String getHeader(String headerName) {
        return this.headers.get(headerName);
    }


    @Override
    public JSONObject toJson() {
        return JsonUtil.toJSON(this.getBody());
    }

    @Override
    public <T> T toEntity(Class<T> classes) {
        return JsonUtil.toJavaObject(this.getBody(), classes);
    }
}

